package com.licode.codekit.utils;

import org.jsoup.internal.StringUtil;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

public class XmlUtil {
    public static Node getNode(Node root, String key) {
        if (null != root) {
            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); ++i) {
                Node node = nodeList.item(i);
                if (node.getNodeName().equals(key)) {
                    return node;
                }
            }
        }
        return null;
    }

    public static String getNodeValue(Node root, String key, String defVal) {
        String val = defVal;
        Node node = getNode(root, key);

        if (null != node) {
            val = node.getTextContent();
        }

        return val;
    }

    public static boolean updateNodeTextValue(Node root, String key, String val) {
        Node node = getNode(root, key);
        if (null != node) {
            node.setTextContent(val);
            return true;
        } else {
            return false;
        }
    }

    public static boolean replaceNodeValue(Node root, String key, Node newNode) {
        Node node = getNode(root, key);
        if (null != node) {
            root.replaceChild(newNode, node);
            return true;
        } else {
            return false;
        }
    }

    public static void removeBlankNodes(Node parent) {
        List<Node> remNodes = new ArrayList<>();
        NodeList nodes = parent.getChildNodes();
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                removeBlankNodes(node);
            }

            if (node.getNodeType() == Node.TEXT_NODE && node instanceof Text) {
                Text text = (Text)node;
                String content = text.getData();
                if (StringUtil.isBlank(content)) {
                    if (content.startsWith("\n\n")) {
                        text.setData("\n");
                        text.setTextContent("\n");
                    } else {
                        remNodes.add(node);
                    }
                }
            }
        }

        for (Node item: remNodes) {
            parent.removeChild(item);
        }
    }
}
